<?php
/* 
* @Author: LDF QQ 47121862
* @Date:   2014-06-07 11:28:36
* @Last Modified by:   LDF QQ 47121862
* @Last Modified time: 2014-06-07 21:16:16
*/
Class UserModel extends Model{
	public $table='user';
	public $validate=array(
		array('email','nonull','邮箱不能为空',2,3),
		array('pwd','nonull','密码不能为空',2,3),
		array('code','nonull','验证码不能为空',1,1)
	);
	public $auto=array(
		array('code','code','method',1,1)
	);

	// 注册用户
	function reg(){
		if($this->create()){
			if(!$this->data['code']) return 0;
			if(!$this->email()) return 0;
			$this->pass(); //组合密码
			if($uid=$this->add()){ //写入数据库和session
				$_SESSION['user']=array(
					'uid'=>$uid,
					'nickname'=>$_POST['nickname'],
					'email'=>$_POST['email'],
					'level'=>0
				);
				return 1;
			}else{
				$this->error='注册失败！';
				return 0;
			}
		}
	}
	//用户登陆
	function login(){
		if($this->create()){
			return $this->checkFrom()?1:0;
		}
	}
	//后台修改用户
	function editUser(){
		$pwd = Q('pwd');
		$data = $this->find(Q('uid',0,'intval'));
		if($data && !empty($pwd)){
			$_POST['pwd'] = md5(md5($pwd).$data['key']);
			return ($this->save($_POST));
		}else{
			unset($_POST['pwd']);
			return $this->save($_POST);
		}
	}
	//==========登陆============
	//检测登陆是否合法
	function checkFrom(){
		$email = Q('email');
		$pwd = Q('pwd');
		$data = $this->where(array('email'=>$email))->find();
		if($data){
			$pwded = md5(md5($pwd).$data['key']);
			if($pwded == $data['pwd']){
				$_SESSION['user']=array(
					'uid'=>$data['uid'],
					'nickname'=>$data['nickname'],
					'email'=>$data['email'],
					'level'=>$data['level']
				);
				return 1;
			} else{
				$this->error='用户名/密码不正确';
				return 0;
			}
		}else{
			$this->error='用户名或密码不正确';
			return 0;
		}
	}
	
	//================注册===================
	//检验验证码
	function code(){
		if(strtolower($_POST['code']) == strtolower($_SESSION['code'])){
			return 1;
		}else{
			$this->error='验证码输入不正确';
			return 0;
		}
	}
	//组合密码
	function pass(){
		$key = substr(md5(time()+mt_rand(0,9999)),0,8);
		$pass = md5(md5($_POST['pwd']).$key);
		$this->data['key']=$key;
		$this->data['pwd']=$pass;
	}
	//检测email是否可以注册
	function email(){
		$email = Q('email');
		$data = $this->where(array('email'=>$email))->find();
		if(!$data){
			$this->data['email']=$email;
			return 1;
		}else{
			$this->error='邮箱已经被注册';
			return 0;
		}
	}
}
